import React, { useEffect } from "react";
import { 
  StyleSheet, 
  Text, 
  View, 
  ScrollView, 
  TouchableOpacity,
  RefreshControl
} from "react-native";
import { Image } from "expo-image";
import { SafeAreaView } from "react-native-safe-area-context";
import { useRouter } from "expo-router";
import { 
  BookOpen, 
  Scan, 
  MessageSquare, 
  Calendar, 
  ChevronRight,
  Sparkles,
  Nfc
} from "lucide-react-native";
import { colors } from "@/constants/colors";
import { Card } from "@/components/Card";
import { Button } from "@/components/Button";
import { useAuthStore } from "@/store/auth-store";
import { useContentStore } from "@/store/content-store";
import { useStudyStore } from "@/store/study-store";

export default function HomeScreen() {
  const router = useRouter();
  const { user } = useAuthStore();
  const { contents, fetchContents, recentlyPlayed } = useContentStore();
  const { startSession, checkIn } = useStudyStore();
  const [refreshing, setRefreshing] = React.useState(false);

  useEffect(() => {
    fetchContents();
  }, []);

  const onRefresh = React.useCallback(async () => {
    setRefreshing(true);
    await fetchContents();
    setRefreshing(false);
  }, [fetchContents]);

  const handleStartLearning = () => {
    if (user) {
      startSession(user.id);
    }
    router.push("/playlist");
  };

  const handleCheckIn = () => {
    if (user) {
      checkIn(user.id);
    }
    router.push("/stats");
  };

  // Get recently played content
  const recentContent = recentlyPlayed
    .map(id => contents.find(content => content.id === id))
    .filter(Boolean)
    .slice(0, 3);

  // Get recommended content (for demo, just show some content not in recently played)
  const recommendedContent = contents
    .filter(content => !recentlyPlayed.includes(content.id))
    .slice(0, 3);

  return (
    <SafeAreaView style={styles.container} edges={["top"]}>
      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
      >
        {/* Header with greeting */}
        <View style={styles.header}>
          <View>
            <Text style={styles.greeting}>Hello, {user?.name || "Friend"}!</Text>
            <Text style={styles.subtitle}>Ready to learn English today?</Text>
          </View>
          {user?.avatar && (
            <Image
              source={{ uri: user.avatar }}
              style={styles.avatar}
              contentFit="cover"
            />
          )}
        </View>

        {/* Quick actions */}
        <View style={styles.quickActions}>
          <TouchableOpacity
            style={styles.actionItem}
            onPress={() => router.push("/playlist")}
          >
            <View style={[styles.actionIcon, { backgroundColor: colors.primary + "20" }]}>
              <BookOpen size={24} color={colors.primary} />
            </View>
            <Text style={styles.actionText}>Learn</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.actionItem}
            onPress={() => router.push("/ocr")}
          >
            <View style={[styles.actionIcon, { backgroundColor: colors.secondary + "20" }]}>
              <Scan size={24} color={colors.secondary} />
            </View>
            <Text style={styles.actionText}>Scan</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.actionItem}
            onPress={() => router.push("/nfc-scan")}
          >
            <View style={[styles.actionIcon, { backgroundColor: colors.accent + "20" }]}>
              <Nfc size={24} color={colors.accent} />
            </View>
            <Text style={styles.actionText}>NFC</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.actionItem}
            onPress={() => router.push("/ai-chat")}
          >
            <View style={[styles.actionIcon, { backgroundColor: colors.success + "20" }]}>
              <MessageSquare size={24} color={colors.success} />
            </View>
            <Text style={styles.actionText}>AI Chat</Text>
          </TouchableOpacity>
        </View>

        {/* Daily streak */}
        <Card style={styles.streakCard} variant="elevated">
          <View style={styles.streakContent}>
            <View>
              <Text style={styles.streakTitle}>Your Learning Streak</Text>
              <Text style={styles.streakSubtitle}>Keep it going!</Text>
            </View>
            <View style={styles.streakCounter}>
              <Text style={styles.streakNumber}>{user?.streak || 0}</Text>
              <Text style={styles.streakDays}>days</Text>
            </View>
          </View>
          <Button
            title="Start Learning"
            onPress={handleStartLearning}
            rightIcon={<ChevronRight size={16} color={colors.text.inverse} />}
          />
        </Card>

        {/* Continue learning */}
        {recentContent.length > 0 && (
          <View style={styles.section}>
            <View style={styles.sectionHeader}>
              <Text style={styles.sectionTitle}>Continue Learning</Text>
              <TouchableOpacity onPress={() => router.push("/playlist")}>
                <Text style={styles.seeAll}>See All</Text>
              </TouchableOpacity>
            </View>

            <ScrollView horizontal showsHorizontalScrollIndicator={false}>
              {recentContent.map((content) => (
                <TouchableOpacity
                  key={content.id}
                  style={styles.contentCard}
                  onPress={() => router.push(`/content/${content.id}`)}
                >
                  <Image
                    source={{ uri: content.imageUrl }}
                    style={styles.contentImage}
                    contentFit="cover"
                  />
                  <View style={styles.contentInfo}>
                    <Text style={styles.contentTitle}>{content.title}</Text>
                    <Text style={styles.contentType}>{content.type}</Text>
                  </View>
                </TouchableOpacity>
              ))}
            </ScrollView>
          </View>
        )}

        {/* Recommended */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionTitle}>Recommended for You</Text>
            <TouchableOpacity onPress={() => router.push("/playlist")}>
              <Text style={styles.seeAll}>See All</Text>
            </TouchableOpacity>
          </View>

          <ScrollView horizontal showsHorizontalScrollIndicator={false}>
            {recommendedContent.map((content) => (
              <TouchableOpacity
                key={content.id}
                style={styles.contentCard}
                onPress={() => router.push(`/content/${content.id}`)}
              >
                <Image
                  source={{ uri: content.imageUrl }}
                  style={styles.contentImage}
                  contentFit="cover"
                />
                {content.difficulty === "beginner" && (
                  <View style={styles.recommendedBadge}>
                    <Sparkles size={12} color={colors.text.inverse} />
                    <Text style={styles.recommendedText}>Best for beginners</Text>
                  </View>
                )}
                <View style={styles.contentInfo}>
                  <Text style={styles.contentTitle}>{content.title}</Text>
                  <Text style={styles.contentType}>{content.type}</Text>
                </View>
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    padding: 16,
    paddingBottom: 100, // Add extra padding at the bottom to prevent content from being hidden by the tab bar
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 24,
  },
  greeting: {
    fontSize: 24,
    fontWeight: "700",
    color: colors.text.primary,
    marginBottom: 4,
  },
  subtitle: {
    fontSize: 16,
    color: colors.text.secondary,
  },
  avatar: {
    width: 48,
    height: 48,
    borderRadius: 24,
  },
  quickActions: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 24,
  },
  actionItem: {
    alignItems: "center",
  },
  actionIcon: {
    width: 56,
    height: 56,
    borderRadius: 16,
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 8,
  },
  actionText: {
    fontSize: 12,
    color: colors.text.secondary,
    fontWeight: "500",
  },
  streakCard: {
    marginBottom: 24,
  },
  streakContent: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 16,
  },
  streakTitle: {
    fontSize: 16,
    fontWeight: "600",
    color: colors.text.primary,
    marginBottom: 4,
  },
  streakSubtitle: {
    fontSize: 14,
    color: colors.text.secondary,
  },
  streakCounter: {
    alignItems: "center",
  },
  streakNumber: {
    fontSize: 24,
    fontWeight: "700",
    color: colors.primary,
  },
  streakDays: {
    fontSize: 12,
    color: colors.text.secondary,
  },
  section: {
    marginBottom: 24,
  },
  sectionHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 16,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "600",
    color: colors.text.primary,
  },
  seeAll: {
    fontSize: 14,
    color: colors.primary,
    fontWeight: "500",
  },
  contentCard: {
    width: 160,
    marginRight: 16,
    borderRadius: 12,
    overflow: "hidden",
    backgroundColor: colors.card,
  },
  contentImage: {
    width: "100%",
    height: 100,
  },
  contentInfo: {
    padding: 12,
  },
  contentTitle: {
    fontSize: 14,
    fontWeight: "600",
    color: colors.text.primary,
    marginBottom: 4,
  },
  contentType: {
    fontSize: 12,
    color: colors.text.tertiary,
    textTransform: "capitalize",
  },
  recommendedBadge: {
    position: "absolute",
    top: 8,
    left: 8,
    backgroundColor: colors.primary,
    borderRadius: 4,
    paddingHorizontal: 8,
    paddingVertical: 4,
    flexDirection: "row",
    alignItems: "center",
    gap: 4,
  },
  recommendedText: {
    fontSize: 10,
    color: colors.text.inverse,
    fontWeight: "500",
  },
});